import React, { useRef, useCallback } from 'react';
import { connect, useDispatch } from 'umi';
import {
  Drawer,
  Form,
  Button,
  Input,
  InputNumber,
  Select,
  DatePicker,
  Divider,
  Switch,
  message,
} from 'antd';
import moment from 'moment';
import PositionManageTable from '@/components/PositionManageTable';
import { ORG_TYPE_LIST } from '@/utils/const';
import useEnum from '@/hooks/useEnum';
import { validateDuplicatedSort } from '../../services';

const { Option } = Select;
const layout = {
  labelCol: { span: 8 },
  wrapperCol: { span: 14 },
};
const convertDataSource = (code, enums, defaultValue) => {
  if (!code || !enums.find((item) => item.code === code)) {
    return defaultValue;
  }
  return enums.find((item) => item.code === code).code;
};

const OrgAddEdit = (props) => {
  const { drawerType, handleClose, handleUpdate, editData, parentId, selectedOrgData = {} } = props;
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const pmtRef = useRef();
  const orgTypeDisabled =
    drawerType === 'edit' || (selectedOrgData.id === parentId && selectedOrgData.orgType === 2);
  // 数据来源字典编码 500
  const dataSourceEnum = useEnum('500');
  // 业务层级字典编码 600
  const businessLevelEnum = useEnum('600');
  // 部门分类字典编码 700
  const departmentClassificationEnum = useEnum('700');

  const sortValidator = useCallback((value) => {
    if (value >= 1 && value <= 9999) {
      return validateDuplicatedSort(value).then((res) => {
        const { code, message: errMessage } = res;
        if (code === 0) {
          return Promise.resolve();
        }
        return Promise.reject(new Error(errMessage));
      });
    }
    return Promise.resolve();
  }, []);

  const handleSubmit = () => {
    const { validateFields } = form;
    validateFields().then((values) => {
      const { expireStartTime, expireEndTime, orgState, ...rest } = values;
      const param = {
        parentId: typeof parentId !== 'undefined' ? parentId : 0,
        expireStartTime: expireStartTime.format('YYYY-MM-DD HH:mm:ss'),
        expireEndTime: expireEndTime && expireEndTime.format('YYYY-MM-DD HH:mm:ss'),
        orgState: orgState ? 1 : 0,
        ...rest,
      };
      let dispatchType = 'orgManageModel/addOrg';
      if (drawerType === 'edit') {
        dispatchType = 'orgManageModel/updateOrg';
        param.id = editData.id;
      }
      dispatch({
        type: dispatchType,
        payload: param,
      }).then((res) => {
        const { code, data, message: errMsg } = res;
        if (code === 0) {
          pmtRef.current?.handleSubmit({
            orgId: data,
            callback: () => {
              message.success('操作成功');
              handleUpdate();
            },
          });
        } else {
          message.error(errMsg);
        }
      });
    });
  };

  const handleFormFieldChange = (changedFields, allFields) => {
    const [{ name }] = changedFields;
    const [fieldName] = name;
    if (fieldName === 'expireStartTime' || fieldName === 'expireEndTime') {
      const expireStartTime = form.getFieldValue('expireStartTime');
      const expireEndTime = form.getFieldValue('expireEndTime');
      if (expireStartTime && expireEndTime && expireEndTime.isBefore(expireStartTime)) {
        form.setFields([
          {
            name: fieldName,
            errors: [
              fieldName === 'expireStartTime'
                ? '起始时间必须小于结束时间'
                : '结束时间必须大于起始时间',
            ],
          },
        ]);
      } else {
        form.setFields([
          { name: 'expireStartTime', errors: [] },
          { name: 'expireEndTime', errors: [] },
        ]);
      }
    }
  };

  return (
    <Drawer
      title={`${drawerType === 'add' ? '添加' : '修改'}组织`}
      width={600}
      visible
      onClose={handleClose}
      bodyStyle={{ paddingBottom: 80 }}
      footer={
        <div style={{ textAlign: 'right' }}>
          <Button onClick={handleClose} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button type="primary" onClick={handleSubmit}>
            {drawerType === 'add' ? '添加' : '保存'}
          </Button>
        </div>
      }
    >
      <Form {...layout} form={form} onFieldsChange={handleFormFieldChange}>
        <div>基本信息</div>
        <Form.Item
          name="orgName"
          label="组织名称"
          rules={[
            {
              required: true,
              message: '请输入组织名称',
            },
            {
              pattern: /^([\u4e00-\u9fa5]|[a-zA-Z0-9]){2,50}$/,
              message: '请输入2-50为中英文、数字组织名称',
            },
          ]}
          initialValue={editData.orgName || editData.title}
        >
          <Input placeholder="输入组织名称" />
        </Form.Item>
        <Form.Item
          name="orgCode"
          label="组织编码"
          rules={[
            { required: true, message: '请输入组织编码' },
            {
              pattern: /^[a-zA-Z0-9]{2,50}$/,
              message: '请输入2-50为英文、数字组织编码',
            },
          ]}
          initialValue={editData.orgCode}
        >
          <Input disabled={editData.orgCode} placeholder="输入组织编码" />
        </Form.Item>
        <Form.Item
          name="orgType"
          label="组织类型"
          rules={[{ required: true, message: '请选择组织类型' }]}
          initialValue={editData.orgType || (orgTypeDisabled ? 2 : undefined)}
        >
          <Select placeholder="选择组织类型" disabled={orgTypeDisabled}>
            {ORG_TYPE_LIST.map((item) => (
              <Option key={item.value} value={item.value}>
                {item.text}
              </Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item label="有效时间范围" required style={{ marginBottom: 0 }}>
          <Form.Item
            name="expireStartTime"
            rules={[{ required: true, message: '请选择有效起始时间' }]}
            initialValue={editData.expireStartTime ? moment(editData.expireStartTime) : undefined}
            style={{ display: 'inline-block', width: 'calc(50% - 12px)' }}
          >
            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder="请选择起始时间" />
          </Form.Item>
          <span
            style={{
              display: 'inline-block',
              width: '24px',
              lineHeight: '32px',
              textAlign: 'center',
            }}
          >
            -
          </span>
          <Form.Item
            name="expireEndTime"
            initialValue={editData.expireEndTime ? moment(editData.expireEndTime) : undefined}
            style={{ display: 'inline-block', width: 'calc(50% - 12px)' }}
          >
            <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" />
          </Form.Item>
        </Form.Item>

        <Form.Item
          name="dataSource"
          label="数据来源"
          rules={[{ required: true, message: '数据来源' }]}
          initialValue={convertDataSource(editData?.dataSource, dataSourceEnum, '501')}
        >
          <Select placeholder="请选择数据来源" disabled>
            {dataSourceEnum.map((item) => (
              <Option key={item.code}>{item.name}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          name="businessLevel"
          label="业务层级"
          rules={[{ required: true, message: '请输入业务层级' }]}
          initialValue={editData.businessLevel || ''}
        >
          <Select placeholder="请选择业务层级">
            {businessLevelEnum.map((item) => (
              <Option key={item.code}>{item.name}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          name="departmentClassification"
          label="部门分类"
          rules={[{ required: true, message: '请输入部门分类' }]}
          initialValue={editData.departmentClassification || ''}
        >
          <Select placeholder="请选择部门分类">
            {departmentClassificationEnum.map((item) => (
              <Option key={item.code}>{item.name}</Option>
            ))}
          </Select>
        </Form.Item>
        <Form.Item
          name="sort"
          label="排序编号"
          rules={[
            // { required: true, message: '请输入排序编号（范围 1~9999）' },
            // {
            //   min: 1,
            //   type: 'number',
            //   message: '最小排序编号为 1',
            // },
            // {
            //   max: 9999,
            //   type: 'number',
            //   message: '最小排序编号为 9999',
            // },
            // ({ getFieldValue }) => ({
            //   validator(_, value) {
            //     return sortValidator(value);
            //   },
            // }),
          ]}
          initialValue={editData.sort}
        >
          <InputNumber
            style={{ width: '100%' }}
            min={1}
            max={9999}
            precision={0}
            placeholder="请输入排序编号（范围 1~9999）"
          />
        </Form.Item>
        <Form.Item
          label="有效性"
          name="orgState"
          valuePropName="checked"
          initialValue={drawerType === 'add' ? true : editData?.orgState === 1}
        >
          <Switch checkedChildren="有效" unCheckedChildren="无效" />
        </Form.Item>

        <Form.Item name="orgDesc" label="描述" initialValue={editData.orgDesc}>
          <Input.TextArea rows={5} maxLength={150} placeholder="输入组织描述，限150字" />
        </Form.Item>

        <Divider type="horizontal" />
        <PositionManageTable ref={pmtRef} orgId={editData.id} />
      </Form>
    </Drawer>
  );
};

export default connect((state) => state)(OrgAddEdit);
